package com.lier.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.lier.gulimall.product.dao.CategoryBrandRelationDao;
import com.lier.gulimall.product.entity.CategoryBrandRelationEntity;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lier.common.utils.PageUtils;
import com.lier.common.utils.Query;

import com.lier.gulimall.product.dao.BrandDao;
import com.lier.gulimall.product.entity.BrandEntity;
import com.lier.gulimall.product.service.BrandService;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Resource
    private CategoryBrandRelationDao categoryBrandRelationDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String)params.get("key");
        LambdaQueryWrapper<BrandEntity> wrapper = new LambdaQueryWrapper<>();
        if(!StringUtils.isEmpty(key)){
            wrapper.eq(BrandEntity::getBrandId, key).or().like(BrandEntity::getName, key);
        }
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void updateDetail(BrandEntity brand) {
        baseMapper.updateById(brand);

        // 级联修改关联表数据
        if(brand.getName() != null){
            LambdaUpdateWrapper<CategoryBrandRelationEntity> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(CategoryBrandRelationEntity::getBrandName, brand.getName())
                    .eq(CategoryBrandRelationEntity::getBrandId, brand.getBrandId());
            categoryBrandRelationDao.update(null, updateWrapper);
        }
    }

}
